<template>
  <div class="work-order-list">
    <!-- <div class="work-order-list-top"> -->
    <CommonHeader
      title="采购入库编辑"
      :is-show-back="true"
      class="header-top"
    />
    <!-- 顶部搜索 -->
    <section class="search-box">
      <div class="inner">
        <van-search
          v-if="activeTab === 0"
          v-model="searchParams.productCode"
          readonly
          placeholder="查询"
          @search="onSearch"
          @cancel="onCancel"
          @click="showSearch"
          @click-right-icon.stop="clear"
        >
          <template #right-icon>
            <van-icon name="cross" />
          </template>
        </van-search>
        <van-search
          v-if="activeTab === 1"
          v-model="searchParams1.compositeSearch"
          readonly
          placeholder="查询"
          @search="onSearch"
          @cancel="onCancel"
          @click="showSearch"
          @click-right-icon.stop="clear"
        >
          <template #right-icon>
            <van-icon name="cross" />
          </template>
        </van-search>
      </div>

      <materialSearchForm
        ref="materialSearchForm"
        v-if="activeTab === 0"
        :search-flag="searchFlag"
        :search-form="searchParams"
        @cancel="handleCancelSearch"
        @confirm="handleConfirmSearch"
      />
      <!-- <batchSearchForm
        ref="batchSearchForm"
        v-if="activeTab === 1"
        :search-flag="searchFlag1"
        :search-form="searchParams1"
        @cancel="handleCancelSearch1"
        @confirm="handleConfirmSearch1"
      /> -->
      <!-- <van-tabs v-model="activeTab" color="#548AF1">
        <van-tab title="物料列表"></van-tab>
        <van-tab title="批次列表"></van-tab>
      </van-tabs> -->
    </section>
    <!-- 顶部搜索 -->
    <!-- 切换区域 -->

    <!-- </div> -->

    <!--  -->
    <listItem :item-obj="infoData">
      <template slot="buttonGorup">
        <div class="num">
          <div class="num-l">入库批次/数量</div>
          <!-- <div class="num-l"></div>  -->
          <div class="num-l">{{ dto[0] || "0/0" }}</div>
        </div>
        <!-- <div class="num">
          <div class="num-l">入库批次</div>
          <div class="num-r"></div>
        </div> -->
      </template>
    </listItem>
    <!--  -->
    <van-tabs
      @change="changeTab()"
      v-model="searchParams.dataState"
      color="#548AF1"
      :ellipsis="false"
    >
      <van-tab
        v-for="(tab, index) in tabs"
        :key="index"
        :name="tab.state"
        :title="tab.title"
      ></van-tab>
    </van-tabs>
    <!-- 内容区域 -->
    <CommonMain v-show="searchParams.dataState == '3'">
      <template>
        <van-pull-refresh
          v-model="refreshing"
          :disabled="isRefreshDisable"
          @refresh="onRefresh"
        >
          <van-list
            v-if="selectInfoList.length > 0"
            v-model="loading"
            :finished="finished"
            finished-text="没有更多了"
            @load="onLoad"
            :immediate-check="false"
          >
            <MateriaItem
              ref="MateriaItem"
              v-for="(item, index) in selectInfoList"
              :key="index"
              :index="index"
              :infoData="infoData"
              :single-material="item"
              :tabState="searchParams.dataState"
              @updateSingleMaterial="updateSingleMaterial"
              @updateMaterialRemark="updateMaterialRemark"
              @updateMaterialExpand="updateMaterialExpand"
              @numDialog="numDialog"
            >
              <template slot="action">
                <el-button @click="printDialog(item)">打印 </el-button>
              </template>
            </MateriaItem>
          </van-list>
        </van-pull-refresh>
      </template>
    </CommonMain>
    <CommonMain v-show="searchParams.dataState != '3'">
      <template>
        <van-pull-refresh
          v-model="refreshing"
          :disabled="isRefreshDisable"
          @refresh="onRefresh"
        >
          <van-list
            v-if="infoList.length > 0"
            v-model="loading"
            :finished="finished"
            finished-text="没有更多了"
            @load="onLoad"
            :immediate-check="false"
          >
            <MateriaItem
              v-for="(item, index) in infoList"
              :key="index"
              :index="index"
              :infoData="infoData"
              :single-material="item"
              :tabState="searchParams.dataState"
              @updateMaterialRemark="updateMaterialRemark"
              @updateMaterialExpand="updateMaterialExpand"
            >
              <template slot="action">
                <el-button @click="printDialog(item)">打印 </el-button>
              </template>
            </MateriaItem>
          </van-list>
        </van-pull-refresh>
      </template>
    </CommonMain>
    <img
      src="@/assets/images/allocation/scan.png"
      class="scan-img"
      v-draggable
      @click="scanChange(false)"
    />
    <footer class="action">
      <section @click="showBottomMore = !showBottomMore" class="more">
        <img src="@/assets/images/more.png" alt="" />
        <span>更多</span>
        <section v-show="showBottomMore" class="popover">
          <el-button
            type="text"
            @click.stop="allSelect"
            v-if="searchParams.dataState == 3 && !this.allChecked"
            >全选</el-button
          >
          <el-button
            type="text"
            @click.stop="allSelectcanel"
            v-if="searchParams.dataState == 3 && this.allChecked"
            >取消全选</el-button
          >
          <el-button
            type="text"
            @click.stop="allSelectdataState"
            v-if="searchParams.dataState != 3 && !this.allCheckedSelect"
            >全选</el-button
          >
          <el-button
            type="text"
            @click.stop="allSelectcaneldataState"
            v-if="searchParams.dataState != 3 && this.allCheckedSelect"
            >取消全选</el-button
          >
          <el-button
            type="text"
            @click.stop="allExpandOrFold"
            v-if="searchParams.dataState == 3"
          >
            {{ isAllExpand ? "全部收起" : "全部展开" }}
          </el-button>
          <el-button
            type="text"
            @click.stop="allExpandOrFolds"
            v-if="searchParams.dataState != 3"
          >
            {{ isAllExpands ? "全部收起" : "全部展开" }}
          </el-button>
          <!-- <el-button type="text"
                style="color:#F82A2A"
                @click.stop="handleDelete"
                >删除</el-button
            > -->
        </section>
      </section>
      <el-button
        type="primary"
        class="btn"
        @click="handleConfirmWarehousing"
        v-if="searchParams.dataState == 3 && infoData.state != 2"
        >提交({{ WarehousingLength }}/{{ materWarehousingLength }})</el-button
      >
      <el-button
        type="primary"
        class="btn"
        @click="handleAddSelectInfoList"
        v-if="searchParams.dataState == 1 && infoData.state != 2"
        >确认已选({{ SlectedLength }}/{{ materSlectedLength }})</el-button
      >
    </footer>
    <!-- dialog -->
    <!-- <sku-dialog :visible.sync="skuVsibel"></sku-dialog> -->
    <!--  -->
    <van-dialog
      v-model="showRealNum"
      title="实际数量"
      show-cancel-button
      confirm-button-color="#548AF1"
      @confirm="realNumHandleConfirm"
      @cancel="realNumHandleCancel"
    >
      <van-form ref="realNumForm" @submit.native.prevent>
        <van-field
          ref="realNumInput"
          name="realNum"
          v-model="realNum"
          type="number"
          label="实际数量"
          :rules="getRealNum()"
          @focus="selectAllTextReal"
        />
      </van-form>
    </van-dialog>
    <van-dialog
      v-model="planAmountshow"
      title="计划数量"
      show-cancel-button
      confirm-button-color="#548AF1"
      :before-close="beforClose"
      @confirm="numHandleConfirm"
      @cancel="numHandleCancel"
    >
      <van-form ref="planAmountForm" @submit.native.prevent>
        <van-field
          ref="planNumInput"
          name="planAmount"
          v-model="planAmount"
          type="number"
          label="计划数量"
          :rules="getPlanAmount()"
          @focus="selectAllTextPlan"
        />
      </van-form>
    </van-dialog>
    <van-popup v-model="showPicker" style="width: 100%" position="bottom">
      <van-picker
        title="批次品质"
        show-toolbar
        :columns="mqList"
        @confirm="onConfirm"
        @cancel="onCancel"
        value-key="label"
        style="width: 100%"
      />
    </van-popup>
    <!--物料特征参数选择弹窗 -->
    <ChoiceSpecificParamsDialog
      v-if="choiceSpecificParamstVisible"
      :show="choiceSpecificParamstVisible"
      :material-code="skuData.stockInventoryDetailEntity.materialFields.code"
      :sku-id="skuData.stockInventoryDetailEntity.skuId"
      @confirm="confirmChoiceSpecificParams"
      @cancel="cancelChoiceSpecificParams"
    />
    <van-dialog
      v-model="show"
      title="完成确认"
      className="sure-dialog"
      show-cancel-button
      confirmButtonColor="#3C76FF"
      @confirm="submitAndCompled"
    >
      <div class="model-content">
        <div class="name">是否完成入库单：</div>
        <div class="value">{{ infoData.orderNumber }}</div>
      </div>
      <div slot="footer" class="dialog-footer">
        <van-button round block type="primary" @click="submitAndCompled"
          >确认</van-button
        >
      </div>
    </van-dialog>
    <!-- 打印 -->
    <print
      v-if="printShow"
      :isShowPrintNum="printShow"
      :currentItem="currentItem"
      :activeTab="activeTab"
      :type="infoData.inOrOutType"
      @handleConfirmPrint="handleConfirmPrint"
      @handleCancelPrint="handleCancelPrint"
    ></print>
    <!-- 扫码新增批次弹窗 -->
    <material-dialog
      v-if="materialShow"
      :show="materialShow"
      :warehouseCode="infoData.warehouseCode"
      :barCode="materialShowBarcode"
      :orderNumber="infoData.orderNumber"
      @handleCancel="materialHandleCancel"
      @handleConfirm="materialHandleConfirm"
    >
    </material-dialog>
    <audio
      style="display: none"
      id="audio"
      ref="audio"
      src="@/assets/audio/正确.mp3"
      muted
      :autoplay="false"
    />
    <van-dialog
      v-model="WarehousingShow"
      className="WarehousingSure-dialog"
      show-cancel-button
      confirmButtonColor="#3C76FF"
      :before-close="WarehousingBeforClose"
      title="入库确认"
    >
      <div class="model-content">
        <div class="name">{{ WarehousingTitle }}</div>
        <div class="value"></div>
      </div>
      <div slot="footer" class="dialog-footer">
        <van-button round block type="primary" @click="submitAndCompled"
          >确认</van-button
        >
      </div>
    </van-dialog>
    <BatchListSelectPopupList
      v-if="showBatchsSelectPopupList"
      style="height: 70vh"
      round
      closeable
      position="bottom"
      :type="type"
      :selectBatchs.sync="selectBatchs"
      v-model="showBatchsSelectPopupList"
      @submitFindSelectedBacths="submitFindSelectedBacths"
      @handleBatchClose="handleBatchClose"
    >
    </BatchListSelectPopupList>
    <!-- 扫码之前选择供应商或者油漆 -->
    <van-dialog
      v-model="handleScanCodeRule"
      className="WarehousingSure-dialog"
      show-cancel-button
      @confirm="scanChange(true)"
      confirmButtonColor="#3C76FF"
      title="解码规则"
    >
      <div class="model-content">
        <el-radio v-model="supplierCode" v-if="orderSupplierCode == '' || orderSupplierCode == 'C025'" label="C025" style="margin-bottom: 10px;">新鸿洲</el-radio>
        <el-radio v-model="supplierCode" v-if="orderSupplierCode == '' || orderSupplierCode == 'C026'" label="C026" style="margin-bottom: 10px;">维科</el-radio>
        <el-radio v-model="supplierCode" v-if="orderSupplierCode == '' || orderSupplierCode == 'C027'" label="C027" style="margin-bottom: 10px;">宝利根</el-radio>
        <el-radio v-model="supplierCode" v-if="orderSupplierCode == '' || orderSupplierCode == '1'" label="1" style="margin-bottom: 10px;">油漆</el-radio>
      </div>
      <div slot="footer" class="dialog-footer">
        <van-button round block type="primary" @click="scanChange(true)"
          >确认</van-button
        >
      </div>
    </van-dialog>
  </div>
</template>

<script>
import materialDialog from "@/components/materialDialog";
import print from "./components/print.vue";
import ChoiceSpecificParamsDialog from "@/components/ChoiceSpecificParamsDialog/index.vue";
// import skuDialog from "./components/skuDialog";
import materialList from "./components/materialList";
import listItem from "../allocation/components/listItem.vue";
import materialSearchForm from "./components/materialSearchForm.vue";
import batchSearchForm from "./components/batchSearchForm.vue";
import CommonHeader from "@/components/CommonHeader/index.vue";
import CommonMain from "@/components/CommonMain/index.vue";
import Item from "./components/item.vue";
import { Dialog, Toast, Tab, Tabs, Form, Col, Row, version } from "vant";
import {
  deleteMaterialDetails,
  deleteMaterial,
  getStockInAndOutById,
  scanCodeRuleGet,
  pdaScanCodeConfirmation,
  updateRemark,
  configShowConfigGetByKey,
} from "@/api/inventory";
import { allocationGetBarDetails } from "@/api/common";
import {
  getList,
  getMaterialList,
  getMaterialDetailsList,
  updateMaterialDetails,
  updateMaterial,
  stateChange,
  addMaterialDetails,
  pdaScanCodeMaterial,
  getPdaMaterialList,
  inUpdateMaterialDetails,
  selectLaunchSimultaneouslyCode,
  infoScanInventory,
  getWorkerOrderCodeList,
  newAddBarCode,
  getNewAddBarCodeProgress,
  suppliersMaterialList,
  getNumRuleDetailByType,
  inventoryRelate,
  planNumCompare,
  getUniqueCheck,
  setUniqueCheck
} from "@/api/inventory";
import Decimal from "decimal.js";
import { decodeFun,fnStr } from './handleBarcodeScan.js'
export default {
  components: {
    CommonHeader,
    CommonMain,
    Item,
    materialSearchForm,
    batchSearchForm,
    ChoiceSpecificParamsDialog,
    listItem,
    // skuDialog,
    materialList,
    materialDialog,
    [Dialog.Component.name]: Dialog.Component,
    [Tab.name]: Tab,
    [Tabs.name]: Tabs,
    [Form.name]: Form,
    [Col.name]: Col,
    [Row.name]: Row,
    print,
    MateriaItem: () => import("./components/MateriaItem.vue"),
    BatchListSelectPopupList: () =>
      import("./components/BatchListSelectPopupList.vue"),
  },
  data() {
    return {
      SlectedLength: 0,
      materSlectedLength: 0,
      selectInfoList: [],
      WarehousingfilteredData: [],
      WarehousingLength: 0,
      materWarehousingLength: 0,
      WarehousingTitle: "",
      WarehousingShow: false,
      isAllExpand: true,
      isAllExpands: true,
      showBottomMore: false,
      show: false,
      submitLoading: false,
      submitLoading1: false,
      /********** */

      /********** */
      showPicker: false,
      searchFlag: false, //搜索框弹出
      searchFlag1: false,
      searchParams: {
        //onload初始化会调用
        current: 0,
        size: 10,
        dataState: 3,
      },
      searchParams1: {
        current: 0,
        size: 10,
        compositeSearch: "",
      },
      activeTab: 0,
      loading: false,
      finished: false,
      refreshing: false,
      loading1: false,
      finished1: false,
      refreshing1: false,
      isRefreshDisable: false,
      // 滚动与下拉冲突
      scrollTop: 0,
      infoData: {
        isToggle: false,
      },
      search: "",
      formModle: {},
      skuVsibel: false,
      infoList: [],
      batchList: [], //批次列表
      mqList: [
        { label: "合格", value: 1 },
        { label: "不合格", value: 0 },
      ],
      currentItem: {},
      choiceSpecificParamstVisible: false,
      //打印
      printShow: false,
      planAmountshow: false,
      planAmount: "",
      showRealNum: false,
      realNum: "",
      currentRealItem: {},
      isScan: false, //是否点击了扫码
      materialShow: false,
      materialShowBarcode: "",
      tabs: [
        {
          title: "已选(0/0)",
          isOutbound: "",
          state: "3",
        },
        {
          title: "待入库(0/0)",
          isOutbound: "0",
          state: "1",
        },
        {
          title: "已入库(0/0)",
          isOutbound: "1",
          state: "5",
        },
      ],
      allChecked: false,
      allCheckedSelect: false,
      index: 0,
      dto: [],

      selectBatchs: [],
      showBatchsSelectPopupList: false,
      type: "",
      scanCode: "",
      oldScanCode: {},
      handleScanCodeRule: false, // 选择解码规则弹窗
      supplierCode: '1', // 解码规则-- 的判断条件
      orderSupplierCode: '', // 采购入库单原本的物料供应商
    };
  },
  watch: {
    scrollTop(newval) {
      if (newval > 0) {
        this.isRefreshDisable = true;
      } else {
        this.isRefreshDisable = false;
      }
    },
    selectInfoList: {
      handler(n) {
        let totalCount = 0;
        let total = 0;
        n.forEach((item) => {
          // if (item.stockMaterialDetaiList.some((detail) => detail.checked)) {
          //   total++;
          // }
          item.stockMaterialDetaiList?.forEach((subItem) => {
            if (subItem.checked === true) {
              totalCount++;
            }
          });
          const data = item.stockMaterialDetaiList.filter(
            (item) => item.checked
          );
          const currentTotal = data.reduce((accumulator, currentValue) => {
            return Decimal(accumulator).add(Decimal(currentValue.realNum));
          }, 0);
          total = Decimal(total).add(currentTotal);
        });
        this.WarehousingLength = totalCount;
        this.materWarehousingLength = total.valueOf();
        if (n.length == 0) {
          this.allChecked = false;
        }
        this.allChecked = n.every((item) => item.checked === true);
      },
      deep: true,
    },
    infoList: {
      handler(n) {debugger
        let totalCount = 0;
        let total = 0;
        n.forEach((item) => {
          // if (item.stockMaterialDetaiList.some((detail) => detail.checked)) {
          //   total++;
          // }
          item.stockMaterialDetaiList?.forEach((subItem) => {
            if (subItem.checked === true) {
              totalCount++;
            }
          });
          const data = item.stockMaterialDetaiList.filter(
            (item) => item.checked
          );
          const currentTotal = data.reduce((accumulator, currentValue) => {
            return Decimal(accumulator).add(Decimal(currentValue.realNum));
          }, 0);
          total = Decimal(total).add(currentTotal);
        });
        this.SlectedLength = totalCount;
        this.materSlectedLength = total.valueOf();
        if (n.length == 0) {
          this.allCheckedSelect = false;
        }
        this.allCheckedSelect = n.every((item) => item.checked === true);
      },
      deep: true,
    },
  },
  async created() {
    await this.getList();
    this.onRefresh();
  },
  beforeDestroy() {
    this.$store.dispatch('permission/setbusinessUnitCodeDetail','')
  },
  mounted() {
    const that = this;
    // PDA扫码
    // window["QrcodeMsg"] = (res) => {
    //   if (res) {
    //     console.log(res, "ScanCodeMsg这是首页");
    //     that.isScan = true;

    //   }
    // };
    // 扫码枪扫码
    window["ScanCodeMsg"] = (res) => {
      if (res) {
        console.log(res, "ScanCodeMsg这是首页");
        that.isScan = true;
        that.scanBarcodeTrackWithoutNumber(res);
      }
    };
  },
  methods: {
    async handleDelete() {
      const data = this.infoList
        .flatMap((item) => item.stockMaterialDetaiList)
        .filter((citem) => citem.checked);
      if (data.length == 0) {
        Toast("请至少选择一条数据");
        return;
      }
      const ids = data.map((item) => item.stockMaterialDetailId);
      const result = await deleteMaterialDetails(ids);
      const { code, message } = result.data;
      if (code == 200) {
        Toast("删除成功");
        this.getList();
        this.onRefresh();
      } else {
        Toast(message);
      }
    },

    async findList(scanResult,scanBarCode) {

      const params = {
        scanCode: scanBarCode,
        orderId: this.$route.query.id,
        warehouseCode: this.infoData.warehouseCode,
        inWarehouse: true,
        materialCode:scanResult.materialCode
      };
      try {
        const result = await infoScanInventory(params);
        const { code, data, message } = result.data;
        if (code == 200) {
          const compare = await this.planNumCompare(scanResult.num || data[0]?.availableStock || data[0]?.count || 0,scanResult.materialCode || data[0]?.materialCode)
          if(compare != 200){
            return
          }
          if (data.length >= 1) {
            //找到了添加批次
            //...
            const res = await this.configShowConfigGetByKey(
              "purchaseEffectAddBarcode"
            );
            if (res == 1) {
              this.type = "添加";
              this.showBatchsSelectPopupList = true;
              this.selectBatchs = data;
              this.selectBatchs.scanObj = scanResult;
            } else {
              Toast.fail("单据无此批次");
            }
          } else if (data.length == 0) {
            //找不到新增
            if (scanResult.rule == 1 && scanResult.isBatchMag) {
              const res = await this.configShowConfigGetByKey(
                "purchaseEffectSelectBarcode"
              );
              if (res == 1) {
                this.getInfoScanInventory(scanResult);
              } else {
                Toast.fail("单据无此批次");
              }
            } else {
              Toast.fail("单据无此批次");
            }
          }
        }
      } catch (error) {
        //没找到则新增批次
        Toast.fail(error.message);
      }
    },

    async getInfoScanInventory(resdata) {
      try {
        this.type = "新增";
        let barCode = `${resdata.supplierMaterialCode || resdata.materialCode || ''}${resdata.barCode || ''}`
        if(this.supplierCode == 'C027') {
          // 按料号+批号+序号
          barCode = `${resdata.supplierMaterialCode || resdata.materialCode || ''}${resdata.barCode || ''}${resdata.serialNumber || ''}`
        } else if(this.supplierCode == 'C026') {
          // 按料号+序列号
          barCode = `${resdata.supplierMaterialCode || resdata.materialCode || ''}${resdata.serialNumber || ''}`
        }
        this.selectBatchs = [
          {
            barCode,
            materialQuality: 1,
            count: resdata.num,
            materialFields: {
              code: resdata.materialCode,
            },
          },
        ];
        this.selectBatchs.scanObj = resdata;
        this.showBatchsSelectPopupList = true;
      } catch (error) {
        Toast.fail(error);
      }
    },
    async inventoryRelate(resdata) {
      const params = { origin: this.scanCode, barCode:  this.selectBatchs[0].barCode || `${resdata.supplierMaterialCode}${resdata.barCode}` };
      await inventoryRelate(params);
    },
    async newAddBarCode(resdata) {
      const numRule = await this.getNumRuleDetailByType();
      
      const params = {
        barCode: this.selectBatchs[0].barCode || resdata.supplierMaterialCode + resdata.barCode,
        relateNumber: this.infoData.orderNumber,
        materialCode: resdata.materialCode,
        moduleType: "purchase",
        num: 1,
        count: resdata.num,
        numberRuleId: numRule[0].id,
      };

      const res = await newAddBarCode(params);
    },
    async getWorkerOrderCodeList(resdata) {

      const {
        data: {
          code,
          data: { records = [] },
        },
      } = await getWorkerOrderCodeList({
        current: 1,
        size: 99999,
        materialCode: resdata.materialCode,
        relateNumber: this.infoData.orderNumber,
        barCode: this.selectBatchs[0].barCode || resdata.supplierMaterialCode + resdata.barCode,
        // barCode: resdata.barCode,
        // skuId: this.formData?.skuId || 0,
      });
      if (code === "200") {
        return records;
      } else {
        return [];
      }
    },
    async getNumRuleDetailByType() {
      const res = await getNumRuleDetailByType({ typeCode: 62 });
      const { data, code, message } = res.data;
      return data;
    },
    async getNewAddBarCodeProgress() {
      return new Promise(async (resolve, reject) => {
        const result = await getNewAddBarCodeProgress({
          relatedNumber: this.infoData.orderNumber,
          type: "purchase",
        });
        const { data, code, message } = result.data;
        let rejectData = [];
        if (code == 200) {
          const {
            progress,
            executionDescription,
            code: innnerCode,
            executionStatus,
          } = JSON.parse(message);
          if (innnerCode == "200") {
            if (executionStatus) {
              resolve(1);
            } else {
              await this.getNewAddBarCodeProgress(orderNumber);
            }
          } else {
            reject(executionDescription);
          }
        }
      });
    },
    handleBatchClose() {
      this.showBatchsSelectPopupList = false;
    },
    async submitFindSelectedBacths(batch) {
      if(this.type == '新增'){
        this.addBatch()
      }else{
        this.findAddBatch(batch)
      }
      if (this.infoData.supplierCode === 'C027' || this.infoData.supplierCode === 'C026') {
        console.log(this.oldScanCode.supplierMaterialCode,'rrrrrr')
        // 验证输入数据
        if (!this.oldScanCode || !this.infoData || !this.infoData.orderNumber) {
          console.error('Invalid input data');
          return;
        }
        const { supplierMaterialCode, barCode, serialNumber, num } = this.oldScanCode;
        // 检查必要字段是否存在
        if (!supplierMaterialCode || !serialNumber || !num) {
          console.error('Missing required fields in scanCode');
          return;
        }
        // 生成 scanCode
        let scanCode;
        if (this.infoData.supplierCode === 'C027') {
          scanCode = supplierMaterialCode + barCode + serialNumber + num;
        } else {
          scanCode = supplierMaterialCode + serialNumber + num;
        }
        // 构建参数对象
        const params = {
          orderNumber: this.infoData.orderNumber,
          scanCode
        };
        try {
          // 调用异步方法并处理结果
          const checkData = await setUniqueCheck(params);
          console.log(checkData);
        } catch (error) {
          // 处理异常
          console.error('Error in setUniqueCheck:', error);
        }
      }

    },
    async findAddBatch(batch){
      const datas = batch.map((item) => {
          return {
            productCode: item.materialFields.code,
            skuId: item.skuId,
            skuCode: item.skuCode,
            skuName: item.skuName,
            materialType: item.materialType,
            type: item.materialFields.type,
            actualNum: "",
            materialQuality: item.materialQuality,
            stockMaterialDetaiList: [
              {
                materialCode: item.productCode,
                skuId: item.skuId,
                skuCode: item.materialFields
                  ? item.materialFields.skuEntity?.skuCode
                  : "",
                skuName: item.materialFields
                  ? item.materialFields.skuEntity?.skuName
                  : "",
                barCode: item.barCode,
                materialQuality: item.materialQuality || "1",
                realNum: this.selectBatchs.scanObj.num || item.availableStock || item.count || 0,
                remark: "",
                isNewAdd: true,
                inventoryDetailId: item.inventoryDetailId || "",
              },
            ],
          };
        });

        const param = {
          id: this.$route.query.id || null,
          materialDetails: datas,
        };
        const res = await addMaterialDetails(param);
        const { code, message, data } = res.data;
        if (code == 200) {
          this.showBatchsSelectPopupList = false;

          await this.getMaterialList();
          this.operation(this.selectBatchs.scanObj,true);
          Toast("添加成功");
        } else {
          throw new Error("批次新增异常！");
        }
    },
    async addBatch(){
      await this.newAddBarCode(this.selectBatchs.scanObj);
      const progress = await this.getNewAddBarCodeProgress(
        this.selectBatchs.scanObj
      );
      if (progress == 1) {
        const records = await this.getWorkerOrderCodeList(
          this.selectBatchs.scanObj
        );

        this.inventoryRelate(this.selectBatchs.scanObj);

        const datas = records.map((item) => {
          return {
            productCode: item.materialFields.code,
            skuId: item.skuId,
            skuCode: item.skuCode,
            skuName: item.skuName,
            materialType: item.materialType,
            type: item.materialFields.type,
            actualNum: "",
            materialQuality: item.materialQuality,
            stockMaterialDetaiList: [
              {
                materialCode: item.productCode,
                skuId: item.skuId,
                skuCode: item.materialFields
                  ? item.materialFields.skuEntity?.skuCode
                  : "",
                skuName: item.materialFields
                  ? item.materialFields.skuEntity?.skuName
                  : "",
                barCode: item.barCode,
                materialQuality: item.materialQuality || "1",
                realNum: item.count || 0,
                remark: "",
                isNewAdd: true,
                inventoryDetailId: item.inventoryDetailId || "",
              },
            ],
          };
        });

        const param = {
          id: this.$route.query.id || null,
          materialDetails: datas,
        };
        const res = await addMaterialDetails(param);
        const { code, message, data } = res.data;
        if (code == 200) {
          this.showBatchsSelectPopupList = false;

          await this.getMaterialList();
          this.operation(this.selectBatchs.scanObj,true);
          Toast("添加成功");
        } else {
          throw new Error("批次新增异常！");
        }
      }
    },
    numDialog() {
      const result = this.selectInfoList.reduce(
        (acc, current) => {
          const stockMaterialDetaiList = current.stockMaterialDetaiList;

          // 计算 stockMaterialDetaiList 的长度
          const listLength = stockMaterialDetaiList.length;

          // 计算 count 的总和
          const countSum = stockMaterialDetaiList.reduce(
            (sum, item) => Decimal(sum).add(Decimal(item.realNum)),
            0
          );

          // 更新累积的长度和总和
          acc.lengthSum += listLength;
          acc.countSum = Decimal(acc.countSum).add(Decimal(countSum));

          return acc;
        },
        { lengthSum: 0, countSum: Decimal(0) }
      );

      this.tabs[0].title = `已选(${result.lengthSum}/${result.countSum})`;
      this.selectInfoList.splice();
    },
    handleAddSelectInfoList() {
      let data = this.infoList.map((item) => {
        return {
          ...item,
          stockMaterialDetaiList: item.stockMaterialDetaiList.filter(
            (detail) => detail.checked !== false
          ),
        };
      });
      data = data.filter((item) => item.stockMaterialDetaiList.length != 0);
      //有全选选中的物料
      let isFirstLevelCheckedTrue = this.infoList.some(
        (item) =>
          item.checked === true && item.stockMaterialDetaiList.length === 0
      );
      if (this.selectInfoList.length == 0) {
        data.map((item) => {
          item.checked = true;
          item.stockMaterialDetaiList.map((citem) => {
            citem.checked = true;
          });
        });
        this.selectInfoList.push(...data);
      } else {
        data.forEach((bItem) => {
          // 在 a 数组中查找匹配的项
          let matchingItem = this.selectInfoList.find(
            (aItem) =>
              aItem.id === bItem.id &&
              aItem.materialEntity.code === bItem.materialEntity.code &&
              aItem.skuId === bItem.skuId
          );
          // 如果找到匹配项
          if (matchingItem) {
            // 遍历 bItem 的 stockMaterialDetaiList
            bItem.stockMaterialDetaiList.forEach((bDetail) => {
              // 在 aItem 的 stockMaterialDetaiList 中查找相同的 inventoryDetailId 的索引
              let aDetailIndex = matchingItem.stockMaterialDetaiList.findIndex(
                (aDetail) =>
                  aDetail.inventoryDetailId === bDetail.inventoryDetailId
              );

              // 如果找到相同的 inventoryDetailId
              if (aDetailIndex !== -1) {
                bDetail.checked = true;
                // 替换相同 inventoryDetailId 的项
                matchingItem.stockMaterialDetaiList.splice(
                  aDetailIndex,
                  1,
                  bDetail
                );
              } else {
                // 如果没有找到相同 inventoryDetailId，则添加到 aItem 的 stockMaterialDetaiList 中
                bDetail.checked = true;
                matchingItem.stockMaterialDetaiList.push(bDetail);
              }
            });
          } else {
            bItem.checked = true;
            bItem.stockMaterialDetaiList.map((citem) => {
              citem.checked = true;
            });
            // 如果没有找到匹配项，则将整个 bItem 添加到 a 数组中
            this.selectInfoList.push(bItem);
          }
        });
      }
      //先赋予初值
      this.selectInfoList.forEach((item) => {
        console.log();
        this.$set(item, "isExpand", true);
        this.$set(item, "checked", item.checked);
        item.stockMaterialDetaiList.map((citem) => {
          this.$set(citem, "checked", citem.checked);
        });
      });
      const result = this.selectInfoList.reduce(
        (acc, current) => {
          const stockMaterialDetaiList = current.stockMaterialDetaiList;

          // 计算 stockMaterialDetaiList 的长度
          const listLength = stockMaterialDetaiList.length;

          // 计算 count 的总和
          const countSum = stockMaterialDetaiList.reduce(
            (sum, item) => Decimal(sum).add(Decimal(item.realNum)),
            0
          );

          // 更新累积的长度和总和
          acc.lengthSum += listLength;
          acc.countSum = Decimal(acc.countSum).add(Decimal(countSum));

          return acc;
        },
        { lengthSum: 0, countSum: Decimal(0) }
      );

      this.tabs[0].title = `已选(${result.lengthSum}/${result.countSum})`;
      this.selectInfoList.splice();
      this.searchParams.dataState = "3";
      this.$nextTick(() => {
        setTimeout(() => {
          document.getElementById("Material" + data[0].id).scrollIntoView();
        });
      });
      let msg = isFirstLevelCheckedTrue
        ? "选中的数据有无批次数据已被过滤"
        : "已移入已选";
      Toast(msg);
    },
    updateSingleMaterial() {
      this.selectInfoList.splice();
    },
    handleConfirmWarehousing() {
      if (this.searchParams.dataState != 3) {
        return;
      }
      const filteredData = this.selectInfoList
        .map((item) => ({
          ...item,
          stockMaterialDetaiList: Array.isArray(item.stockMaterialDetaiList)
            ? item.stockMaterialDetaiList.filter(
                (subItem) => subItem.checked !== false
              )
            : [],
        }))
        .filter(
          (item) =>
            item.checked === true || item.stockMaterialDetaiList.length > 0
        );
      console.log("data", filteredData);
      if (filteredData.length == 0) {
        Toast({
          className: "myToast jinggao",
          message: "请至少勾选一条数据",
          position: "top",
        });
      } else {
        let indexs = [];
        for (let i = 0; i < filteredData.length; i++) {
          for (let j = 0; j < this.selectInfoList.length; j++) {
            if (filteredData[i].id == this.selectInfoList[j].id) {
              indexs.push(j);
              break;
            }
          }
        }
        console.log("this.$refs.MateriaItem[item]", this.$refs.MateriaItem[0]);
        const validatePromises = indexs.map((item) => {
          return new Promise((resolve, reject) => {
            console.log(
              "this.$refs.MateriaItem",
              item,
              this.$refs.MateriaItem[item].$refs
            );
            this.$refs.MateriaItem[
              item
            ].$refs.materialtable.$refs.form.validate((valid) => {
              console.log("validvalidvalid", valid);
              if (valid) {
                resolve();
              } else {
                reject();
              }
            });
          });
        });
        Promise.all(validatePromises)
          .then((results) => {
            this.WarehousingfilteredData = filteredData;
            this.WarehousingBeforClose("confirm", function () {});
            // console.log("resultsresultsresults", results);
            // this.WarehousingShow = true;

            // this.WarehousingTitle = filteredData.some(
            //   (item) =>
            //     !item.stockMaterialDetaiList ||
            //     item.stockMaterialDetaiList.length === 0
            // )
            //   ? "入库单无此物料或批次信息，请确认!"
            //   : "是否确认当前勾选物料入库";
          })
          .catch((err) => {});
      }
    },
    async WarehousingBeforClose(action, done) {
      if (action == "confirm") {
        const params = this.WarehousingfilteredData.flatMap(
          ({ stockMaterialDetaiList }) =>
            stockMaterialDetaiList.map((item) => ({
              ...item,
              dataState: 5,
            }))
        );
        const result = await inUpdateMaterialDetails(params);

        const remarks = this.WarehousingfilteredData.map((item) => {
          return {
            id: item.id,
            materialRemark: item.materialRemark,
          };
        });
        await updateRemark(remarks);

        const { data, code, message } = result.data;
        if (code == 200) {
          this.selectInfoListHandleDelelte();
          this.searchParams.dataState = "5";

          const getSimultaneouslyData = await selectLaunchSimultaneouslyCode(
            "auto_complete_purchase",
            this.infoData.orderNumber
          );
          const { data: Simultaneously } = getSimultaneouslyData.data;

          if (Simultaneously) {
            await this.changeState(this.$route.query.id, 2);
          }
          done();
          this.getList();
          this.onRefresh();
        } else {
          Toast.fail(message);
          done();
        }
      } else {
        done();
      }
    },
    async changeState(id, state) {
      const res = await stateChange({ id, state });
      let { data } = res;
    },
    selectInfoListHandleDelelte() {
      // 找到在a数组中与b数组中id相同的项
      let matchingItems = this.selectInfoList.filter((aItem) =>
        this.WarehousingfilteredData.some((bItem) => aItem.id === bItem.id)
      );

      // 遍历匹配的项
      matchingItems.forEach((matchingItem) => {
        // 在a数组里面stockMaterialDetaiList里面的inventoryDetailId相等的项删除
        matchingItem.stockMaterialDetaiList =
          matchingItem.stockMaterialDetaiList.filter((aDetail) => {
            let bItem = this.WarehousingfilteredData.find(
              (bItem) => bItem.id === matchingItem.id
            );
            if (bItem) {
              return !bItem.stockMaterialDetaiList.some(
                (bDetail) =>
                  bDetail.inventoryDetailId === aDetail.inventoryDetailId
              );
            }
            return true;
          });
      });

      // 删除stockMaterialDetaiList的长度为0的项
      this.selectInfoList = this.selectInfoList.filter(
        (aItem) => aItem.stockMaterialDetaiList.length > 0
      );
      this.$refs.MateriaItem.forEach((item) => {
        console.log("item", item.$refs.materialtable);
        item.$refs.materialtable.updataTable();
      });
      const result = this.selectInfoList.reduce(
        (acc, current) => {
          const stockMaterialDetaiList = current.stockMaterialDetaiList;

          // 计算 stockMaterialDetaiList 的长度
          const listLength = stockMaterialDetaiList.length;

          // 计算 count 的总和
          const countSum = stockMaterialDetaiList.reduce(
            (sum, item) => Decimal(sum).add(Decimal(item.realNum)),
            0
          );

          // 更新累积的长度和总和
          acc.lengthSum += listLength;
          acc.countSum = Decimal(acc.countSum).add(Decimal(countSum));

          return acc;
        },
        { lengthSum: 0, countSum: Decimal(0) }
      );

      this.tabs[0].title = `已选(${result.lengthSum}/${result.countSum})`;
    },
    changeTab() {
      if (this.searchParams.dataState == "3") {
        return;
      }
      this.onRefresh();
    },
    allExpandOrFold() {
      this.isAllExpand = !this.isAllExpand;
      this.selectInfoList.map((item) => {
        if (this.isAllExpand) {
          item.isExpand = true;
        } else {
          item.isExpand = false;
        }
      });
    },
    allExpandOrFolds() {
      this.isAllExpands = !this.isAllExpands;
      this.infoList.map((item) => {
        if (this.isAllExpands) {
          item.isExpand = true;
        } else {
          item.isExpand = false;
        }
      });
    },
    allSelect() {
      this.selectInfoList.map((item) => {
        item.checked = true;
        item.stockMaterialDetaiList.map((citem) => {
          citem.checked = true;
        });
      });
      this.selectInfoList.slice();
    },
    allSelectcanel() {
      this.selectInfoList.map((item) => {
        item.checked = false;
        item.stockMaterialDetaiList.map((citem) => {
          citem.checked = false;
        });
      });
      this.selectInfoList.slice();
    },
    allSelectdataState() {
      this.infoList.map((item) => {
        item.checked = true;
        item.stockMaterialDetaiList.map((citem) => {
          citem.checked = true;
        });
      });
      this.infoList.splice();
    },
    allSelectcaneldataState() {
      this.infoList.map((item) => {
        item.checked = false;
        item.stockMaterialDetaiList.map((citem) => {
          citem.checked = false;
        });
      });
      this.infoList.splice();
    },
    updateMaterialExpand(val) {},
    updateMaterialRemark() {},
    // 播放音频
    playAudio(isSuccess) {
      // const audioElement = document.getElementById('audio')
      const audioElement = this.$refs.audio;
      // audioElement
      audioElement.src = isSuccess
        ? require("@/assets/audio/正确.mp3")
        : require("@/assets/audio/错误.mp3");
      this.$nextTick(() => {
        try {
          audioElement.paused && audioElement.play();
        } catch (error) {
          console.log(error);
        }
      });
    },
    // 解码 refund-outbound-app.material-out.handleScanCode.barCode
    async scanCodeRuleGet(scanCode) {
      try {
        const params = {
          code: "purchaseWarehousing.handleBarcodeScan.new",
        };
        const {
          data: { code, data },
        } = await scanCodeRuleGet(params);
        if (code === "200") {
          // 如果有配置解码规则
          if (data.value) {
            const fn = new Function(`return ${data.value}`)();
            // const result = fn(scanCode, this.infoData.supplierCode || "");
            const result = fn(scanCode, this.supplierCode || "");
            console.log(result,'result---解码后的结果')
            this.scanCode = scanCode;
            this.oldScanCode = result
            //   this.playAudio(true);
            return result;
          } else {
            //  this.playAudio(true);
            return scanCode;
          }
        }
      } catch (error) {
        this.playAudio(false);
        console.log(error,'=====')
        return "";
      }
    },

    // 扫码解码
    async scanBarcodeTrackWithoutNumber(res) {
      const that = this;
      res = await this.scanCodeRuleGet(res);
      console.log(res,'解码规则接出来的结果')
      if (this.activeTab == 0) {
        if (this.loading) {
          return;
        }
        // this.searchParams.productCode = res;
        // this.materialShowBarcode = res;
        // this.onRefresh();
        if (this.infoData.state != 2) {
          this.operation(res);
        }
      } else {
        if (this.loading1) {
          return;
        }
        this.searchParams1.compositeSearch = res;
        this.materialShowBarcode = res;
        this.onRefresh1();
      }
    },
    async planNumCompare(num,productCode){
      const params = {
        inOrOutType:this.infoData.inOrOutType,
        orderId:this.$route.query.id,
        productCode:productCode,
        num:num
      }
      const res = await planNumCompare(params)
      const {code,message,data} = res.data
      if(code != 200){
        Toast.fail(message)
      }
      return code
    },
    async operation(res,isAdd) {
      // try {
        if (res.rule == 1) {
          // 针对C027和C026进行校验唯一性
          if(!isAdd) {
            if(this.infoData.supplierCode == 'C027' || this.infoData.supplierCode == 'C026') {
              let scanCode = this.infoData.supplierCode == 'C027' ? (res.supplierMaterialCode + res.barCode + res.serialNumber + res.num) : (res.supplierMaterialCode + res.serialNumber + res.num)
              let params = {
                orderNumber: this.infoData.orderNumber,
                scanCode
              }
              const checkData = await getUniqueCheck(params)
              console.log(checkData,'判断唯一性')
              if(checkData.data.code == 200) {
                if(!checkData.data.data) { // 如果是false ，则表示重复了
                  Toast.fail('不允许重复扫入批次，请重新扫码')
                  return
                }
              }
            }
          }
          this.setScanList(res,isAdd);
        } else if (res.rule == 2) {
          this.getScanList(res,isAdd);
        }else{
          const obj = {
            rule:2,
            barCode:res
          }
          this.getScanList(obj,isAdd);
        }
      // } catch (error) {
      //   console.log(error, '扫描失败')
      // }
    },
    async scanUpdate(data, scanResult) {
      data.map((item) => {
        item.realNum = Decimal(item.realNum || 0).add(Decimal(scanResult.num || 0)).toNumber()
        item.stockMaterialDetaiList[0].realNum = Decimal(item.stockMaterialDetaiList[0].realNum || 0).add(Decimal(scanResult.num || 0)).toNumber()
        // item.stockMaterialDetaiList.map((citem) => {
        //   citem.realNum =
        //     Number(citem.realNum || 0) + Number(scanResult.num || 0);
        // });
      });
      const params = data.flatMap((item) => item.stockMaterialDetaiList);
      const result  =  await inUpdateMaterialDetails(params);
      const {code,message} = result.data
      params.map(item=>{
        item.version += 1
      })
      return code
    },
    async getScanMaterialCode(scanResult) {
      // const params = {supplierMaterialCode:scanResult.supplierMaterialCode,supplierCode:this.infoData.supplierCode || 'TOM100100'}
      const params = {
        supplierMaterialCode: scanResult.supplierMaterialCode,
        supplierCode: this.infoData.supplierCode || "S-00001",
      };
      const res = await suppliersMaterialList(params);
      const { data, code, message } = res.data;
      return data[0] || {};
    },

    async setScanList(scanResult, isAdd,type) {
      let scanBarCode = `${scanResult.supplierMaterialCode || scanResult.materialCode || ''}${scanResult.barCode || ''}`
      if(this.supplierCode == 'C027') {
        // 按料号+批号+序号
        scanBarCode = `${scanResult.supplierMaterialCode || scanResult.materialCode || ''}${scanResult.barCode || ''}${scanResult.serialNumber || ''}`
      } else if(this.supplierCode == 'C026') {
        // 按料号+序列号
        scanBarCode = `${scanResult.supplierMaterialCode || scanResult.materialCode || ''}${scanResult.serialNumber || ''}`
      }
      const params = {
        orderNumber: this.$route.query.orderNo || this.infoData.orderNumber,
        scanCode:
          type == "scend"
            ? scanResult.materialCode
            : scanBarCode,
        // scanCode:
        //   type == "scend"
        //     ? scanResult.materialCode
        //     : scanResult.barCode,
        // scanCode: scanResult.barCode ,
        inOrOutType: this.infoData.inOrOutType,
        warehouseCode: this.infoData.warehouseCode,
      };
      try {
        const res = await pdaScanCodeMaterial(params);
        let { data } = res.data;

        const filterData = data.filter(
          (item) => item.stockMaterialDetaiList.length == 0
        );
        if (filterData.length > 0) {
          Toast.fail("扫码的数据内包含无批次物料，已被过滤");
          data = data.filter((item) => item.stockMaterialDetaiList.length != 0);
        }
        if (!scanResult.materialCode && scanResult.supplierMaterialCode) {
          const supplierData = await this.getScanMaterialCode(scanResult);
          if (!supplierData.materCode) {
            Toast.fail("该码的物料不在系统内");
            return;
          }
          scanResult.materialCode = supplierData.materCode;
          scanResult.isBatchMag = supplierData.materialFields.isBatchMag;
          if (!scanResult.isBatchMag) {
            console.log(
              "scanResult.supplierMaterialCode + scanResult.barCode",
              scanResult.supplierMaterialCode + scanResult.barCode
            );
            const params = { origin: this.scanCode, barCode: `${scanResult.materialCode}` };
            await inventoryRelate(params);
            this.setScanList(scanResult,false, "scend");
            return;
          }else{
            const params = { origin: this.scanCode, barCode: scanBarCode };
            await inventoryRelate(params);
          }
        }

        if (data.length > 0) {
          let stateData = data.map((item) => {
            return {
              ...item,
              stockMaterialDetaiList: item.stockMaterialDetaiList.filter(
                (item) => item.dataState != 5
              ),
            };
          });
          stateData = stateData.filter(
            (item) => item.stockMaterialDetaiList.length != 0
          );
          // if (stateData.length > 0) {
            //扫的数量累计
            if(stateData.length > 0){
              if(!isAdd ){
                const compareCode = await this.planNumCompare(scanResult.num,data[0].productCode || data[0].materialEntity.code)
                if(compareCode != 200){
                  return
                }
                const updateCode = await this.scanUpdate(data, scanResult);
                if(updateCode != 200){
                  return
                }
              }
            }

            console.log(data)
            // await this.updateMaterialDetails(this.batchList)
            if (this.selectInfoList.length == 0) {
              data.map((item) => {
                item.checked = true;
                item.stockMaterialDetaiList.map((citem) => {
                  citem.checked = true;
                });
              });
              this.selectInfoList.push(...data);
            } else {
              data.forEach((bItem) => {
                // 在 a 数组中查找匹配的项
                let matchingItem = this.selectInfoList.find(
                  (aItem) =>
                    aItem.materialEntity.code === bItem.materialEntity.code &&
                    aItem.skuId === bItem.skuId
                );
                // 如果找到匹配项
                if (matchingItem) {
                  // 遍历 bItem 的 stockMaterialDetaiList
                  bItem.stockMaterialDetaiList.forEach((bDetail) => {
                    // 在 aItem 的 stockMaterialDetaiList 中查找相同的 inventoryDetailId 的索引
                    let aDetailIndex =
                      matchingItem.stockMaterialDetaiList.findIndex(
                        (aDetail) =>
                          aDetail.inventoryDetailId ===
                          bDetail.inventoryDetailId
                      );

                    // 如果找到相同的 inventoryDetailId
                    if (aDetailIndex !== -1) {
                      bDetail.checked = true;
                      // 替换相同 inventoryDetailId 的项
                      matchingItem.realNum = bDetail.realNum
                      matchingItem.stockMaterialDetaiList.splice(
                        aDetailIndex,
                        1,
                        bDetail
                      );
                    } else {
                      // 如果没有找到相同 inventoryDetailId，则添加到 aItem 的 stockMaterialDetaiList 中
                      bDetail.checked = true;
                      matchingItem.stockMaterialDetaiList.push(bDetail);
                    }
                  });
                } else {
                  bItem.checked = true;
                  bItem.stockMaterialDetaiList.map((citem) => {
                    citem.checked = true;
                  });
                  // 如果没有找到匹配项，则将整个 bItem 添加到 a 数组中
                  this.selectInfoList.push(bItem);
                }
              });
            }
            //先赋予初值
            this.selectInfoList.forEach((item) => {
              this.$set(item, "isExpand", true);
              this.$set(item, "checked", item.checked);
              // this.$set(
              //   item,
              //   "realNum",
              //   Decimal(item.realNum || 0).add(Decimal(scanResult.num || 0)).toNumber()
              // );
              item.stockMaterialDetaiList.map((citem) => {
                this.$set(citem, "checked", citem.checked);
              });
            });
            const result = this.selectInfoList.reduce(
              (acc, current) => {
                const stockMaterialDetaiList = current.stockMaterialDetaiList;

                // 计算 stockMaterialDetaiList 的长度
                const listLength = stockMaterialDetaiList.length;

                // 计算 count 的总和
                const countSum = stockMaterialDetaiList.reduce(
                  (sum, item) => Decimal(sum).add(Decimal(item.realNum)),
                  0
                );

                // 更新累积的长度和总和
                acc.lengthSum += listLength;
                acc.countSum = Decimal(acc.countSum).add(Decimal(countSum));

                return acc;
              },
              { lengthSum: 0, countSum: Decimal(0) }
            );

            this.tabs[0].title = `已选(${result.lengthSum}/${result.countSum})`;
            this.selectInfoList.splice();
            this.onRefresh()
            this.searchParams.dataState = "3";
            this.$nextTick(() => {
              setTimeout(() => {
                document
                  .getElementById("Material" + data[0].id)
                  .scrollIntoView();
              });
            });
            Toast("已移入已选");
            console.log("citem", this.selectInfoList);
          // }else{
          //   //只存在已入库数据
          //   this.searchParams.dataState = "5";
          //   this.onRefresh();
          //   this.$nextTick(() => {
          //     setTimeout(() => {
          //       document
          //         .getElementById("Material" + data[0].id)
          //         .scrollIntoView();
          //     });
          //   });
          // }
        } else {

          this.findList(scanResult, scanBarCode);
        }
      } catch (error) {
        console.log(error);
      }
    },

    async getScanList(scanResult) {
      let scanBarCode = `${scanResult.supplierMaterialCode || scanResult.materialCode || ''}${scanResult.barCode || ''}`
      if(this.supplierCode == 'C027') {
        // 按料号+批号+序号
        scanBarCode = `${scanResult.supplierMaterialCode || scanResult.materialCode || ''}${scanResult.barCode || ''}${scanResult.serialNumber || ''}`
      } else if(this.supplierCode == 'C026') {
        // 按料号+序列号
        scanBarCode = `${scanResult.supplierMaterialCode || scanResult.materialCode || ''}${scanResult.serialNumber || ''}`
      }
      const params = {
        orderNumber: this.$route.query.orderNo,
        scanCode: scanResult.barCode,
        inOrOutType: this.infoData.inOrOutType,
        warehouseCode: this.infoData.warehouseCode,
      };
      try {
        const res = await pdaScanCodeMaterial(params);
        let { data } = res.data;
        // data.map((item) => (item.realNum = item.actualAmount));
        const filterData = data.filter(
          (item) => item.stockMaterialDetaiList.length == 0
        );
        if (filterData.length > 0) {
          Toast.fail("扫码的数据内包含无批次物料，已被过滤");
          data = data.filter((item) => item.stockMaterialDetaiList.length != 0);
        }
        if (!scanResult.barCode) {
          scanResult.barCode = scanResult.materialCode;
          this.getScanList(scanResult);
          return;
        }

        if (data.length > 0) {
          let stateData = data.map((item) => {
            return {
              ...item,
              stockMaterialDetaiList: item.stockMaterialDetaiList.filter(
                (item) => item.dataState != 5
              ),
            };
          });
          stateData = stateData.filter(
            (item) => item.stockMaterialDetaiList.length != 0
          );
          // if (stateData.length > 0) {
            if (this.selectInfoList.length == 0) {
              data.map((item) => {
                item.checked = true;

                item.stockMaterialDetaiList.map((citem) => {
                  citem.checked = true;
                  if(!item.materialEntity.isBatchMag){
                    item.realNum = citem.realNum;
                  }
                });
              });
              this.selectInfoList.push(...data);
            } else {
              data.forEach((bItem) => {
                // 在 a 数组中查找匹配的项
                let matchingItem = this.selectInfoList.find(
                  (aItem) =>
                    aItem.materialEntity.code === bItem.materialEntity.code &&
                    aItem.skuId === bItem.skuId
                );
                // 如果找到匹配项
                if (matchingItem) {
                  // 遍历 bItem 的 stockMaterialDetaiList
                  bItem.stockMaterialDetaiList.forEach((bDetail) => {
                    // 在 aItem 的 stockMaterialDetaiList 中查找相同的 inventoryDetailId 的索引
                    let aDetailIndex =
                      matchingItem.stockMaterialDetaiList.findIndex(
                        (aDetail) =>
                          aDetail.inventoryDetailId ===
                          bDetail.inventoryDetailId
                      );

                    // 如果找到相同的 inventoryDetailId
                    if (aDetailIndex !== -1) {
                      bDetail.checked = true;
                      // 替换相同 inventoryDetailId 的项
                      matchingItem.realNum = bDetail.realNum
                      matchingItem.stockMaterialDetaiList.splice(
                        aDetailIndex,
                        1,
                        bDetail
                      );
                    } else {
                      // 如果没有找到相同 inventoryDetailId，则添加到 aItem 的 stockMaterialDetaiList 中
                      bDetail.checked = true;
                      matchingItem.stockMaterialDetaiList.push(bDetail);
                    }
                  });
                } else {
                  bItem.checked = true;
                  bItem.stockMaterialDetaiList.map((citem) => {
                    citem.checked = true;
                  });
                  // 如果没有找到匹配项，则将整个 bItem 添加到 a 数组中
                  this.selectInfoList.push(bItem);
                }
              });
            }
            //先赋予初值
            this.selectInfoList.forEach((item) => {
              console.log();
              this.$set(item, "isExpand", true);
              this.$set(item, "checked", item.checked);
              item.stockMaterialDetaiList.map((citem) => {
                this.$set(citem, "checked", citem.checked);
              });
            });
            const result = this.selectInfoList.reduce(
              (acc, current) => {
                const stockMaterialDetaiList = current.stockMaterialDetaiList;

                // 计算 stockMaterialDetaiList 的长度
                const listLength = stockMaterialDetaiList.length;

                // 计算 count 的总和
                const countSum = stockMaterialDetaiList.reduce(
                  (sum, item) => Decimal(sum).add(Decimal(item.realNum)),
                  0
                );

                // 更新累积的长度和总和
                acc.lengthSum += listLength;
                acc.countSum = Decimal(acc.countSum).add(Decimal(countSum));

                return acc;
              },
              { lengthSum: 0, countSum: Decimal(0) }
            );

            this.tabs[0].title = `已选(${result.lengthSum}/${result.countSum})`;
            this.selectInfoList.splice();
            this.searchParams.dataState = "3";
            this.$nextTick(() => {
              setTimeout(() => {
                document
                  .getElementById("Material" + data[0].id)
                  .scrollIntoView();
              });
            });
            Toast("已移入已选");
            console.log("citem", this.selectInfoList);
          // } else {
          //   //只存在已入库数据
          //   this.searchParams.dataState = "5";
          //   this.onRefresh();
          //   this.$nextTick(() => {
          //     setTimeout(() => {
          //       document
          //         .getElementById("Material" + data[0].id)
          //         .scrollIntoView();
          //     });
          //   });
          // }
        } else {
          //生效后是否允许添加批次
          this.findList(scanResult,scanBarCode);
        }
      } catch (error) {
        Toast.fail(error.message);
        console.log(error);
      }
    },
    clear() {
      if (this.activeTab == 0) {
        this.$refs.materialSearchForm.cancel();
      } else {
        this.$refs.batchSearchForm.cancel();
      }
    },
    selectAllTextPlan() {
      this.$refs.planNumInput.$refs.input.select();
    },
    selectAllTextReal() {
      this.$refs.realNumInput.$refs.input.select();
    },
    materialHandleCancel() {
      this.materialShow = false;
      this.isScan = false;
      // 取消搜索
      if (this.activeTab == 0) {
        this.searchParams.productCode = "";
        this.materialShowBarcode = "";
        this.onRefresh();
      } else {
        this.searchParams1.compositeSearch = "";
        this.materialShowBarcode = "";
        this.onRefresh1();
      }
    },
    async materialHandleConfirm(paramsData) {
      await this.materialSubmit(paramsData);
      this.materialShow = false;
      this.isScan = false;
      if (this.activeTab == 0) {
        this.onRefresh();
      } else {
        this.onRefresh1();
      }
    },
    async materialSubmit(paramsData) {
      const { form, records } = paramsData || {};
      const datas = {
        productCode: form.productCode,
        skuId: form.skuId,
        skuCode: form.skuCode,
        skuName: form.skuName,
        materialType: form.materialType,
        type: form.type,
        actualNum: "",
      };
      const stockMaterialDetaiList = records.map((item) => {
        return {
          materialCode: form.productCode,
          skuId: item.skuId,
          skuCode: item.materialFields
            ? item.materialFields.skuEntity?.skuCode
            : "",
          skuName: item.materialFields
            ? item.materialFields.skuEntity?.skuName
            : "",
          barCode: item.barCode,
          materialQuality: form.materialQuality || "1",
          realNum: form.realNum,
          // saleMaterialId: this.$route.query.id,
          remark: "",
          isNewAdd: true,
          inventoryDetailId: item.inventoryDetailId || "",
        };
      });
      const materialDetails = {
        ...datas,
        materialQuality: form.materialQuality,
        stockMaterialDetaiList: stockMaterialDetaiList || [],
      };
      const param = {
        id: this.$route.query.id || null,
        materialDetails: [materialDetails],
      };
      const result = await addMaterialDetails(param);
      const { code, message, data } = result.data;
      if (code == 200) {
        this.$emit("handleConfirm");
      } else {
        throw new Error("批次新增异常！");
      }
    },
    // 实际数量修改
    realNumDialog(item) {
      if (!(this.infoData.state == 0 || this.infoData.state == 1)) {
        return;
      }
      const obj = JSON.parse(JSON.stringify(item));
      this.currentRealItem = item;
      this.realNum = obj.realNum;
      this.showRealNum = true;
    },
    realNumHandleConfirm() {
      this.$refs.realNumForm
        .validate("realNum")
        .then(async (res) => {
          this.currentRealItem.realNum = this.realNum;
          this.showRealNum = false;
          this.currentRealItem = {};
          await this.updateMaterialDetails(this.batchList);
        })
        .catch((err) => {
          this.showRealNum = true;
        });
    },
    realNumHandleCancel() {
      this.currentRealItem = {};
      this.showRealNum = false;
    },
    planAmountDialog(item) {
      if (!(this.infoData.state == 0 || this.infoData.state == 1)) {
        return;
      }
      const obj = JSON.parse(JSON.stringify(item));
      this.currentItem = item;
      this.planAmount = obj.planAmount;
      this.planAmountshow = true;
    },
    beforClose(action, done) {
      if (action == "confirm") {
        if (!this.planAmountshow) {
          done();
        } else {
          done(false);
        }
      } else {
        done();
      }
    },
    numHandleConfirm() {
      this.$refs.planAmountForm.validate("planAmount").then((res) => {
        this.currentItem.planAmount = this.planAmount;
        this.planAmountshow = false;
        this.currentItem = {};
        this.updateMaterial(this.infoList);
      });
    },
    numHandleCancel() {
      this.currentItem = {};
      this.planAmountshow = false;
    },
    handleConfirmPrint() {
      this.printShow = false;
    },
    handleCancelPrint() {
      this.printShow = false;
    },
    printDialog(item) {
      const hasCheckedLength = item.stockMaterialDetaiList.filter(
        (item) => item.checked
      );
      if (hasCheckedLength == 0) {
        Toast("请至少选中一条数据");
        return;
      }
      this.printShow = true;
      this.currentItem = item;
    },
    getPlanAmount(item) {
      return [
        {
          item,
          validator: this.validatorPlanAmount,
          message: "计划数量不能为空,不能小于等于0",
          trigger: "onBlur",
        },
      ];
    },
    getRealNum(item) {
      return [
        {
          item,
          validator: this.validatorRealNum,
          message: "实际数量不能为空,不能小于等于0",
          trigger: "onBlur",
        },
      ];
    },
    getRule(item) {
      return [
        {
          item,
          validator: this.validator,
          message: "请输入实际数量",
          trigger: "onBlur",
        },
      ];
    },
    validator(val, rule) {
      if (!val) {
        return false;
      }
      if (val <= 0) {
        return false;
      } else {
        return true;
      }
    },
    validatorPlanAmount(val, rule) {
      if (!val) {
        return false;
      }
      if (val < 0) {
        return false;
      } else {
        return true;
      }
    },
    validatorRealNum(val, rule) {
      if (!val) {
        return false;
      }
      if (val <= 0) {
        return false;
      } else {
        return true;
      }
    },
    confirmChoiceSpecificParams(data) {
      this.skuData.skuId = data.skuId;
      this.skuData.skuCode = data.skuCode;
      this.skuData.skuName = data.skuName;
      this.choiceSpecificParamstVisible = false;
    },
    cancelChoiceSpecificParams() {
      this.choiceSpecificParamstVisible = false;
    },
    deleteMaterial(id) {
      this.isScan = false;
      Dialog.confirm({
        title: "删除",
        message: "确认删除此物料",
        confirmButtonColor: "#548AF1",
      }).then(async () => {
        // on confirm
        await deleteMaterial({ materialId: id });
        this.onRefresh();
      });
    },
    deleteMaterialDetails(id) {
      this.isScan = false;
      Dialog.confirm({
        title: "删除",
        message: "确认删除此批次",
        confirmButtonColor: "#548AF1",
      }).then(async () => {
        // on confirm
        await deleteMaterialDetails([id]);
        this.onRefresh1();
      });
    },
    isDisable(text) {
      const result =
        this.infoData.state === 1 || this.infoData.state === 0 ? false : true;
      if (this.activeTab === 0) {
        const obj = {
          planAmount: result,
          remark: result,
        };
        return obj[text];
      } else {
        const obj = {
          planAmount: result,
          remark: result,
          count: result,
          stockLocationQuantity: result,
          materialQualityName: result,
        };
        return obj[text];
      }
    },
    updateMaterialDetails(data) {
      return new Promise(async (resolve, reject) => {
        try {
          const {
            data: { code, data: data1 },
          } = await updateMaterialDetails(data);
          if (code == 200) {
            // console.log(data1, "data1");

            // this.batchList.forEach(i)
            data1.forEach((i) => {
              const index = this.batchList.findIndex(
                (batch) =>
                  batch.stockMaterialDetailId === i.stockMaterialDetailId
              );
              if (index > -1) {
                this.batchList[index].version = i.version;
              }
            });
            Toast.success("提交成功");
            resolve();
          }
        } catch (error) {
          this.onRefresh1();
        }
      });
    },
    updateMaterial(data) {
      return new Promise(async (resolve, reject) => {
        const {
          data: { code },
        } = await updateMaterial(data);
        if (code == 200) {
          Toast.success("提交成功");
          resolve();
        }
      });
    },
    async getList() {
      const {
        data: { data: infoData, code },
      } = await getStockInAndOutById({
        id: this.$route.query.id,
        querySupplier: 1,
      });
      this.infoData = infoData;
      if(this.infoData.businessUnitCode){
        this.$store.dispatch('permission/setbusinessUnitCodeDetail',this.infoData.businessUnitCode)
      }
      this.supplierCode = this.infoData?.supplierCode || '1'
      this.orderSupplierCode = this.infoData?.supplierCode || ''
    },
    async getMaterialList() {
      console.log("this.infoData.orderNumber", this.infoData.orderNumber);
      const params = {
        ...this.searchParams,
        orderNumber: this.infoData.orderNumber,
        warehouseCode: this.infoData.warehouseCode,
        inOrOutType: this.infoData.inOrOutType,
      };
      this.loading = true;
      this.refreshing = true;
      const {
        data: {
          data: { records, total, dto, current },
        },
      } = await getPdaMaterialList(params);
      this.loading = false;
      this.refreshing = false;
      if (current > 1) {
        this.infoList = [...this.infoList, ...records];
      } else {
        this.infoList = records;
      }
      this.infoList.map((item) => {
        this.$set(item, "isExpand", true);
        this.$set(item, "checked", false);
        item.stockMaterialDetaiList?.map((citem) => {
          this.$set(citem, "checked", false);
        });
      });
      // this.tabs[0].title = `已选(0)`;
      this.tabs[1].title = `待入库(${dto[0] || "0/0"})`;
      this.tabs[2].title = `已入库(${dto[1] || "0/0"})`;
      this.dto = dto;
      if (this.infoList.length >= total) {
        this.finished = true;
      }
    },
    materialDialogShow() {
      this.materialShow = true;
    },
    async getMaterialDetailsList() {
      const params = {
        ...this.searchParams1,
        orderNumber: this.infoData.orderNumber,
      };
      this.loading1 = true;
      this.refreshing1 = true;
      const {
        data: {
          data: { records, total },
        },
      } = await getMaterialDetailsList(params);
      this.loading1 = false;
      this.refreshing1 = false;
      if (records) {
        records.map((item) => {
          item.stockInventoryDetailEntity.materialQualityName =
            item.stockInventoryDetailEntity.materialQuality == 1
              ? "合格"
              : "不合格";
        });
      }
      if (this.searchParams1.current > 1) {
        this.batchList = [...this.batchList, ...records];
      } else {
        this.batchList = records;
      }
      if (this.infoData.state != 2) {
        if (this.isScan) {
          if (this.batchList.length == 0) {
            this.materialDialogShow();
          } else {
            this.isScan = false;
          }
        }
      }

      if (this.batchList.length >= total) {
        this.finished1 = true;
      }
    },
    async configShowConfigGetByKey(orderType) {
      const res = await configShowConfigGetByKey(orderType);
      const { code, data, message } = res.data;
      return data.propertyValue;
    },

    scanChange(type) {
      console.log(type,'type------')
      if(!type && !this.orderSupplierCode) {
        return this.handleScanCodeRule = true
      }
      const that = this;
      that.isScan = true;
      this.index++;
      if (process.env.NODE_ENV === "development") {
        let newTime = (new Date()).getTime()
        let a = [
          // "CKPC20241202002",
          // "GN266XA;SX;HSG,BOT,CAMBRIDGERIE312GRY#3;CKPC20241202017;100;ABS/19878400;00071449-P;B.1;13",
          // "10@SX@B_2-03035-000193#CKPC20241202020#0515",
          // "1000@21216789@B_2-03032-000193#20240611#0009",
          "1000@8500201@B_2-03032-000193#20240611#0008",
          "2302198016665-W230106093;SX;10;CKPC" + newTime,
          "2302198016665-W230106011;SX;10;CKPC20241202023",
          "2302198016665-W230106012;SX;10;CKPC20241202024",
          "2302198016665-W230106013;SX;10;CKPC20241202025",
          "200@test-1845-ceshi@#CK202407160002#",
          "boli",
          "boli",
          "100@XYD-TOM100100@#CK2024070801212#",
          "200@test-1845-ceshi@#CK202407160002#",
          "test0328-txcs/kg000120240523123/20",
          "20240202-CGSH013",
        ];
        that.scanBarcodeTrackWithoutNumber(a[this.index - 1]);
        // that.decodeFun(a[this.index - 1]);
      } else {
        window.flutter_inappwebview.callHandler("qrCode").then((res) => {
          if (res) {
            console.log(res, "qrCode");
            that.scanBarcodeTrackWithoutNumber(res);
          }
        });
      }
    },

    chsoeMq(item) {
      this.showPicker = true;
      this.currentItem = item;
    },
    // 点击picker取消按钮
    onCancel() {
      this.showPicker = false;
    },
    // 点击picker确定按钮
    onConfirm(e) {
      this.currentItem.stockInventoryDetailEntity.materialQuality = e.value;
      this.currentItem.stockInventoryDetailEntity.materialQualityName = e.label;
      console.log(this.currentItem);
      this.showPicker = false;
    },
    // 打开picker
    openPicker() {
      if (!this.isShowSubmitBtn) {
        return;
      }
      this.showPicker = true;
    },

    // 提交
    submitData() {
      Dialog.alert({
        title: "物料入库确认",
        message: `确定物料入库操作？`,
        showCancelButton: true,
      }).then(() => {
        this.submit();
      });
    },
    //提交并完成
    async submitAndCompled() {
      if (this.activeTab == 0) {
        this.submitLoading1 = true;
        await this.updateMaterial(this.infoList);
        const {
          data: { code, message },
        } = await stateChange({
          id: this.$route.query.id,
          state: 2,
          type: "purchase",
        });
        if (code == 200) {
          this.$router.push("/allocation");
        } else {
          Toast(message);
        }
        this.submitLoading1 = false;
      } else {
        this.submitLoading1 = true;
        this.$refs.vantForm
          .validate()
          .then(async () => {
            await this.updateMaterialDetails(this.batchList);
            const {
              data: { code },
            } = await stateChange({
              id: this.$route.query.id,
              state: 2,
              type: "purchase",
            });
            if (code == 200) {
              this.$router.push("/allocation");
            }
            this.submitLoading1 = false;
          })
          .catch(() => {
            this.submitLoading1 = false;
          });
      }
    },
    //提交并完成
    async submit() {
      if (this.activeTab == 0) {
        await this.updateMaterial(this.infoList);
        this.$router.push("/allocation");
      } else {
        this.$refs.vantForm.validate().then(async () => {
          await this.updateMaterialDetails(this.batchList);
          this.$router.push("/allocation");
        });
      }
    },
    // 弹出搜索框
    showSearch() {
      if (this.activeTab == 0) {
        this.searchFlag = !this.searchFlag;
      } else {
        this.searchFlag1 = !this.searchFlag1;
      }
    },
    // 搜索
    onSearch() {},
    // 取消搜索
    onCancel() {
      this.searchFlag = false;
    },
    // 确认搜索
    handleConfirmSearch(val) {
      this.searchParams = val;
      let detaultParams = {
        current: this.searchParams.current,
        size: this.searchParams.size,
      };
      this.searchParams = { ...detaultParams, ...val };
      this.searchFlag = false;
      this.searchParams.dataState = "1";
      this.onRefresh();
    },
    // 重置搜索
    handleCancelSearch(val) {
      let detaultParams = {
        current: this.searchParams.current,
        size: this.searchParams.size,
      };
      this.searchParams = { ...detaultParams, ...val };
      this.searchFlag = false;
      this.onRefresh();
    },
    // 确认搜索
    handleConfirmSearch1(val) {
      this.searchParams1 = val;
      let detaultParams1 = {
        current: this.searchParams.current,
        size: this.searchParams.size,
      };
      this.searchParams = { ...detaultParams1, ...val };
      this.searchFlag1 = false;
      this.onRefresh1();
    },
    // 重置搜索
    handleCancelSearch1(val) {
      let detaultParams = {
        current: this.searchParams.current,
        size: this.searchParams.size,
      };
      this.searchParams1 = { ...detaultParams, ...val };
      this.searchFlag1 = false;
      this.onRefresh1();
    },
    // 加载更多
    onLoad() {
      if (this.finished) {
        return;
      }
      console.log("滚到了底部");
      this.searchParams.current += 1;
      this.getList().then(() => {
        this.getMaterialList();
      });
      // this.getMaterialList();
    },
    onLoad1() {
      if (this.finished1) {
        return;
      }
      console.log("滚到了底部");
      this.searchParams1.current += 1;
      this.getMaterialDetailsList();
    },
    // 下拉刷新
    onRefresh() {
      // 清空列表数据
      this.finished = false;
      this.searchParams.current = 1;
      this.getMaterialList();
    },
    onRefresh1() {
      // 清空列表数据
      this.finished1 = false;
      this.searchParams1.current = 1;
      this.getMaterialDetailsList();
    },
    changeTabs() {
      if (this.activeTab == 0) {
        this.onRefresh();
      } else {
        this.onRefresh1();
      }
    },
    toMateral(id) {
      this.$router.push({
        path: "/materialDetail",
        query: {
          id: id,
          orderNo: this.infoData.orderNumber,
          warehouseCode: this.infoData.warehouseCode,
          Oid: this.$route.query.id,
          warehouseCode: this.infoData.warehouseCode,
        },
      });
      localStorage.setItem("orderNumber", this.infoData.orderNumber);
      localStorage.setItem("id", id);
    },
    onSubmit() {},
    skuDialog(data) {
      console.log(data, "=====");
      this.choiceSpecificParamstVisible = true;
      this.skuData = data;
    },
    toBacth() {
      this.$router.push({
        path: "/allocationDetail/form",
        query: {
          id: this.$route.query.id,
          orderNumber: this.infoData.orderNumber,
          warehouseCode: this.infoData.warehouseCode,
        },
      });
    },
    async getInfo() {
      const id = this.$route.query.id;
      const {
        data: { data: infoData, code },
      } = await getDetail(id); //物料详情
      const {
        data: { data: infoList },
      } = await getMaterials({ osOrderId: id }); //物料列表
      let batchList = [];
      infoList.forEach((item) => {
        const arr = item.osorderMaterialDetaiList || [];
        arr.forEach((citem) => {
          //批次列表
          citem.stockInventoryDetailEntity.materialName = citem.materialName;
          citem.stockInventoryDetailEntity.materialQualityName =
            citem.stockInventoryDetailEntity.materialQuality == 1
              ? "合格"
              : "不合格";
          batchList.push(citem.stockInventoryDetailEntity);
        });
      });
      this.loading = false;
      this.finished = true;
      infoData.isToggle = false;
      this.infoData = infoData;
      this.infoList = infoList;
      this.batchList = batchList;


    },
  },
};
</script>

<style lang="scss" scoped>
@import "../../assets/css/common.scss";
.main-content {
  // height: auto;
  // min-height: calc(100vh - 200px);
  // margin-top: 135px;
  // background-image: linear-gradient(180deg, #548af1 0%, #84afff 72%, #ffffff 100%);
  // background-size:  100% 100px;
  // background-repeat: no-repeat;
  // position: relative;
  // z-index: 1;
}
.work-order-list {
  position: relative;
  width: 100vw;
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #f6f6f6;
  ::v-deep .van-tabs__nav {
    background: #f5f8f9;
  }
  .work-order-list-top {
    position: fixed;
    width: 100%;
    left: 0;
    top: 0;
    z-index: 2;
  }
  .search-box {
    // height: 46px;
    position: relative;
    .inner {
      font-size: 16px;
      color: #fff;
      padding: 8px 12px;
      background-color: #ffffff;
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    .van-search {
      flex: 1;
      padding: 0px 15px 0 3px;
      // height: 32px;
      border-radius: 4px;
      border: 1px #dedede solid;
    }
    .van-search__content {
      background-color: #ffffff;
      height: 32px;
      .van-cell {
        height: 30px;
        display: flex;
        align-items: center;
      }
    }
    .btn-wrap {
      width: 62px;
      height: 32px;
      background: #548af1;
      border-radius: 4px;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-left: 7px;
      font-size: 14px;
      color: #fff;
    }
    .scan-box {
      display: flex;
      align-items: center;
      img {
        width: 20px;
      }
    }
  }
  .van-pull-refresh {
    height: calc(100% - 75px);
    overflow: scroll;
    /deep/ .van-pull-refresh__track {
      // overflow: scroll;
    }
    .van-list {
      height: 100%;
      // overflow: scroll;
    }
    .no-data {
      height: 100%;
      font-size: 14px;
      display: flex;
      justify-content: center;
      color: #c7c6c6;
      padding-top: 30px;
    }
  }
  .detail-box {
    width: 100%;
    display: flex;
    justify-content: center;
    background: linear-gradient(180deg, #548af1 0%, #84afff 72%, #ffffff 100%);
    height: 150px;
    margin-bottom: 38px;
    .detail {
      width: 94%;
      height: 147px;
      padding: 17px 7px 10px 7px;
      background: #ffffff;
      box-shadow: 0px 3px 6px rgba(0, 0, 0, 0.16);
      border-radius: 8px;
      margin-bottom: 12px;
      z-index: 1;
      .d-1 {
        display: flex;
        justify-content: space-between;
        padding-bottom: 8px;
        margin-bottom: 9px;
        border-bottom: 1px solid #f3f3f3;
        .d-1-l {
          display: flex;
          img {
            width: 18.27px;
            height: 20px;
          }
          .idbox {
            font-size: 16px;
            font-family: Source Han Sans CN;
            font-weight: bold;
            color: #333333;
            margin-left: 8px;
          }
        }
      }
      .d-row {
        margin-bottom: 8px;
        font-size: 14px;
        font-family: Source Han Sans CN;
        font-weight: 400;
        display: flex;
      }
      .d-l {
        color: #666666;
        margin-right: 8px;
      }
      .d-r {
        color: #333333;
      }
      .status {
        width: 39px;
        height: 20px;
        background: #ffffff;
        border: 1px solid #666666;
        border-radius: 2px;
        font-size: 12px;
        font-family: Source Han Sans CN;
        font-weight: 400;
        text-align: center;
        margin-right: 8px;
        display: flex;
        justify-content: center;
        align-items: center;
        &.take-effect {
          color: #0db45b;
          border: 1px solid #0db45b;
        }
        &.complete {
          color: #548af1;
          border: 1px solid #548af1;
        }
      }
    }
  }
  .no-data {
    height: 100%;
    font-size: 14px;
    display: flex;
    justify-content: center;
    color: #c7c6c6;
    padding-top: 30px;
  }
  .btnbox {
    display: flex;
    justify-content: space-around;
    align-items: center;
    padding: 9px 40px;
    background: #ffffff;
    .l-img {
      width: 22.47px;
      height: 24.96px;
    }
    .btn {
      width: 331px;
      height: 46px;
      background: #548af1;
      box-shadow: 0px 4px 8px rgba(8, 9, 29, 0.1);
      border-radius: 44px;
      font-size: 16px;
      font-family: Source Han Sans CN;
      font-weight: 500;
      color: #ffffff;
      margin: 0 12px 0 14px;
      display: flex;
      justify-content: center;
      align-items: center;
    }

    .btn-no {
      width: 331px;
      height: 46px;
      background: #dbdbdb;
      box-shadow: 0px 4px 8px rgba(8, 9, 29, 0.1);
      border-radius: 44px;
      font-size: 16px;
      font-family: Source Han Sans CN;
      font-weight: 500;
      color: #ffffff;
      margin: 0 12px 0 14px;
      display: flex;
      justify-content: center;
      align-items: center;
    }
    .r-img {
      width: 55px;
      height: 55px;
    }
  }
  .tabbar {
    width: 100%;
    padding: 10px 15px;
    background: #ffffff;
    position: fixed;
    left: 0;
    bottom: 0;
    // bottom: constant(safe-area-inset-bottom); /* iOS */
    // bottom: env(safe-area-inset-bottom); /* Android */
    display: flex;
    justify-content: space-around;
  }
  .action {
    // height: 64px;
    z-index: 99;
    background: #ffffff;
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    padding: 9px 22px 9px 15px;
    display: flex;
    justify-content: space-between;
    min-height: 46px;
    .more {
      display: flex;
      align-items: center;
      position: relative;
      span {
        font-size: 14px;
        font-family: Source Han Sans CN, Source Han Sans CN;
        font-weight: 400;
        color: #666666;
        margin-left: 10px;
      }
      .popover {
        position: absolute;
        bottom: 48px;
        left: -10px;
        width: 105px;
        height: 76px;

        background: #ffffff;
        box-shadow: 0px 3px 6px 1px rgba(0, 0, 0, 0.16);
        opacity: 1;
        font-size: 17px;
        font-family: Source Han Sans CN, Source Han Sans CN;
        font-weight: 400;
        color: #548af1;
        text-align: center;
        line-height: 35px;
        display: flex;
        flex-direction: column;
        .el-button {
          flex: 1;
          margin: 0;
          border-bottom: 1px solid #f2f2f2;
        }
        // section {
        //   height: 35px;
        // }
        // section:nth-of-type(1) {
        //   border: 1px solid #f2f2f2;
        // }
      }
    }
    .btn {
      width: 264px;
      height: 46px;
      // background: #548af1;
      // box-shadow: 0px 4px 8px 1px rgba(8, 9, 29, 0.1);
      // border-radius: 4px 4px 4px 4px;
      // line-height: 46px;
      // font-weight: 400;
      // color: #ffffff;
      // text-align: center;
    }
  }
  .list-content-headerTitle {
    font-size: 16px;
    font-family: Source Han Sans CN-Medium, Source Han Sans CN;
    font-weight: 500;
    color: #333333;
    margin-bottom: 12px;
  }
  .list-content-title {
    font-size: 16px;
    font-family: Source Han Sans CN-Regular, Source Han Sans CN;
    font-weight: 400;
    color: #333333;
    margin-bottom: 12px;
  }
  .list-content-bottom {
    margin-top: 15px;

    .imgBox {
      text-align: right;

      img {
        width: 20px;
        height: 20px;
        margin-left: 10px;
      }
    }
  }
  .van-col {
    margin-bottom: 10px !important;
  }
  .title {
    width: 74px;
    font-size: 15px;
    font-family: SourceHanSansCN-Regular-, SourceHanSansCN-Regular;
    font-weight: normal;
    color: #666666;
  }

  .textContent {
    display: flex;

    align-items: center;
    .title {
    }
    ::v-deep .van-field {
      width: 73px;
      padding: 0;
      height: 28px;
      line-height: 28px;
      border-radius: 4px;
      border: 1px solid #dcdfe6;
      padding: 0 15px;
      &.van-field--error {
        border: 1px solid #ee0a24;
      }
    }
  }
}
.picker-box {
  width: 100%;
  background-color: #548af1;
  display: flex;
  justify-content: center;
  padding: 10px 0;
}
.select-box {
  width: 94%;
  height: 42px;
  margin-top: 5px;
  background-color: #ffffff;
  border-radius: 10px;
  display: flex;
  flex-direction: row;
  align-items: center;
  padding: 10px;
  .select-label {
    color: #7e7e7e;
  }
  .select-box-item {
    flex: 1;
    word-break: break-all;
    overflow: hidden;
    text-overflow: ellipsis;
    font-size: 14px;
  }
}
.scan-img {
  position: fixed;
  bottom: 13.5vh;
  right: 0;
  // transform: translateX(-50%);
  width: 82px;
  height: 82px;
  z-index: 2;
}
.scan-bg {
  flex: 0 1 40px;
  width: 40px;
  height: 40px;
  border-radius: 100%;
  background-color: #dbdbdb;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
  box-shadow: 0 4px 8px #e6e6e6;
  img {
    width: 20px;
    height: 20px;
  }
}
.model-content {
  padding: 25px 10px 20px 26px;
  .name {
    font-size: 14px;
    color: #666666;
  }
  .value {
    font-size: 16px;
    color: #548af1;
    margin-top: 10px;
  }
}
.num {
  display: flex;
  min-width: 64px;
  padding: 6px;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  .num-l {
    font-size: 10px;
    font-family: Source Han Sans CN, Source Han Sans CN;
    font-weight: 400;
    color: #333333;
  }
  .num-r {
    font-size: 12px;
    font-family: Source Han Sans CN, Source Han Sans CN;
    font-weight: 400;
    color: #f29a21;
  }
  &:nth-child(1) {
    background: rgba(255, 242, 223, 0.52);
    border-radius: 2px 2px 2px 2px;
    border: 1px solid #fbb240;
    margin-right: 4px;
    .num-l {
      color: #f29a21;
    }
  }
  &:nth-child(2) {
    background: #e7ffe6;
    border-radius: 2px 2px 2px 2px;
    border: 1px solid #48ba47;
    .num-l {
      color: #48ba47;
    }
    .num-r {
      color: #48ba47;
    }
  }
}
</style>
